export default class TodoModel {
  constructor() {
    this.todoText = '';
    this.todoData = [
      // {
      //   id: 1,
      //   content: 'vue',
      //   completed: false
      // },
      // {
      //   id: 2,
      //   content: 'react',
      //   completed: true
      // },
      // {
      //   id: 3,
      //   content: 'angular',
      //   completed: false
      // }
    ];
  }

  static create() {
    if (!TodoModel.instance) {
      TodoModel.instance = new TodoModel();
    }
    //返回单例
    return TodoModel.instance;
  }

  setTodoText(text) {
    this.todoText = text;
  }

  addTodo(text, callback) {
    const todo = {
      id: new Date().getTime(),
      content: text,
      completed: false
    };
    this.todoData.push(todo);
    doCallback(callback, todo);
    this.setTodoText('');
  }

  toggleTodo(id, callback) {
    this.todoData = this.todoData.map((item) => {
      if (item.id === id) {
        item.completed = !item.completed;
      }
      return item;
    });
    doCallback(callback, id);
  }

  removeTodo(id, callback) {
    this.todoData = this.todoData.filter((item) => item.id !== id);
    doCallback(callback, id);
  }
}

function doCallback(callback, arg) {
  typeof callback === 'function' && callback(arg);
}
